import pgzrun
import random
import os
import json

os.environ['SDL_VIDEO_CENTERED'] = '1'

storage = {
    'highscore': 0,  # 最高分数
    'play_time': 0,  # 挑战次数
    'game_status': -1,  # 0 is end 1 is start -1 is prepare
}

with open('data.json', 'rb') as file:
    data = json.load(file)
    print("加载配置：", data)
    storage['highscore'] = data['highscore']
    storage['play_time'] = data['play_time']

TITLE = 'Flappy Bird'
WIDTH = 288  # 游戏宽度
HEIGHT = 500  # 游戏高度

# These constants control the difficulty of the game
GAP = 130  # 管道间固定间距，方便bird通过
GRAVITY = 0.3
FLAP_STRENGTH = 6.5
SPEED = 3

# bird
bird = Actor('bluebird-midflap.png', (75, 200))
bird.dead = False
bird.score = 0
bird.vy = 0

storage['play_time'] += 1

def reset_pipes():
    # 设置随机的高度 top + bottom + gap = HEIGHT
    pipe_gap_y = random.randint(200, 300)  # 随机生成管道中间
    pipe_top.pos = (WIDTH + 26, 0)  # 顶部管道绘制点，上面的管道缩短
    pipe_bottom.pos = (WIDTH, 500 - 320 + 160)  # 底部管道绘制点，下面的管道增高


pipe_top = Actor('pipe-green.png', anchor=('center', 'center'))
pipe_top.angle = 180
pipe_bottom = Actor('pipe-green.png', anchor=('left', 'top'))
reset_pipes()

game_over = Actor('gameover.png', anchor=('center', 'center'))
game_over.pos = (WIDTH/2, HEIGHT/2)

prepare_view = Actor('message.png', anchor = ('center', 'center'))
prepare_view.pos = (WIDTH/2, HEIGHT/2)


def update_pipes():
    # 不断的移动柱子
    pipe_top.left -= SPEED
    pipe_bottom.left -= SPEED
    if pipe_top.right < 0:
        reset_pipes()
        if not bird.dead:
            bird.score += 1
            sounds.point.play()
            if bird.score > storage['highscore']:
                storage['highscore'] = bird.score
                with open('data.json', 'w') as data_file:
                    write_json = json.JSONEncoder().encode(storage)
                    data_file.write(write_json)


def update_bird():
    # 小鸟下降
    uy = bird.vy
    bird.vy += GRAVITY
    bird.y += (uy + bird.vy) / 2
    bird.x = 75

    # 切换小鸟的造型
    if not bird.dead:
        if bird.vy < -3:
            bird.image = 'bluebird-downflap.png'
        elif bird.vy > 0:
            bird.image = 'bluebird-upflap.png'
        elif bird.vy == 0:
            bird.image = 'bluebird-midflap.png'

    # 判断小鸟死亡： 是否触碰柱子
    if bird.colliderect(pipe_top) or bird.colliderect(pipe_bottom):
        sounds.hit.play()
        storage['game_status'] = 0

    # 小鸟超过边界 初始化
    if not 0 < bird.y < 720:
        sounds.die.play()
        storage['game_status'] = 0
    #     bird.y = 200
    #     bird.dead = False
    #     bird.score = 0
    #     bird.vy = 0
    #     reset_pipes()


def game_end():
    # 游戏结束
    bird.y = -100
    bird.dead = True
    bird.image = 'redbird-midflap.png'
    game_over.draw()
    reset_pipes()
    storage['game_status'] = 0


def update():
    if storage['game_status'] == 1:
        update_pipes()
        update_bird()
    else:
        pass

def on_mouse_down():
    game_status = storage['game_status']
    if game_status == -1 or game_status == 0:
        storage['game_status'] = 1
        bird.dead = False
        bird.score = 0
        bird.vy = 0
        bird.y = HEIGHT / 2
        reset_pipes()
        print('game again')
        return
    if game_status == 1:
        if not bird.dead:
            sounds.wing.play()
            bird.vy = -FLAP_STRENGTH
        return



# 按下任意键， 小鸟上升
def on_key_down(key):
    if not bird.dead:
        sounds.wing.play()
        bird.vy = -FLAP_STRENGTH
    if key == keys.SPACE:
        storage['game_status'] = 1
        bird.dead = False
        bird.score = 0
        bird.vy = 0
        bird.y = HEIGHT/2
        reset_pipes()
        print('game again')


#
def draw():
    # 背景
    screen.blit('background-day.png', (0, 0))

    if storage['game_status'] == 1:
        play()

    if storage['game_status'] == -1:
        prepare()
        draw_best()

    if storage['game_status'] == 0:
        game_end()
        draw_best()

def prepare():
    prepare_view.draw()


def play():
    # 加载小鸟/柱子
    pipe_top.draw()
    pipe_bottom.draw()
    bird.draw()

    if storage['game_status'] == 0:
        game_over.draw()


    draw_score()
    draw_best()

def on_music_end():
    print('music end')


def draw_score():
    # 显示分数
    screen.draw.text(
        str(bird.score),
        color='white',
        midtop=(WIDTH // 2, 10),
        fontsize=70,
        shadow=(1, 1)
    )

def draw_best():
    screen.draw.text(
        "Best: {}".format(storage['highscore']),
        color=(200, 170, 0),
        midbottom=(WIDTH // 2, HEIGHT - 10),
        fontsize=30,
        shadow=(1, 1)
    )

music.play('manxian.mp3')
pgzrun.go()
